/**
* 系统管理 用户管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/indicator/indicatorList' }">指标集列表</el-breadcrumb-item>
      <el-breadcrumb-item >{{formInline.name}}</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="padding:5px;color:#000000;text-align: center;font-family:PingFang SC;font-size:30px">指标详情</div>
    <el-row class="indicator-table-container">
      <el-col :span="18" class="content">
        <!-- 表格内容 -->
        <el-table :data="indicatorListData" style="width: 100%;" class="custom-table">
          <el-table-column
            prop="indicator"
            label="指标"
            width="765">
            <template slot-scope="scope">
              <div class="indicator-cell">
                <span>{{ scope.row.indicator }}</span>
                <el-button
                  v-if="isEditing"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  class="small-delete-button"
                  @click="handleDelete(scope.row.indicator)">
                </el-button>
              </div>
            </template>
          </el-table-column>

        </el-table>
      </el-col>
      <el-col :span="6" class="action-buttons">
        <!-- 编辑和保存按钮 -->
        <el-button-group class="button-group">
          <el-button type="primary" size="small" @click="edit">编辑</el-button>
          <el-button type="primary" size="small" v-if="isEditing" @click="save('editForm')">保存</el-button>
          <el-button type="success" size="small" v-if="isEditing" @click="addIndicator">新增</el-button>
        </el-button-group>
      </el-col>
      <!-- 选择example数据的弹出框 -->
      <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="50%" class="custom-dialog">
        <el-select v-model="selectedIndicators" multiple placeholder="请选择指标" @change="handleSelectChange" class="custom-select">
          <el-option
            v-for="item in exampleData"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
      </span>
      </el-dialog>
    </el-row>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

  </div>
</template>

<script>
  // 导入请求方法
  import {
    userList,
    userSave,
    userDelete,
    userPwd,
    userExpireToken,
    userFlashCache,
    userLock,
    UserDeptTree,
    UserDeptSave,
    UserDeptdeptTree,
    UserChangeDept, targetList
  } from '../../api/userMG'
  import Pagination from '../../components/Pagination'
  import axios from "axios";
  export default {
    data() {
      return {
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        loading: false, //是显示加载
        title: '添加条件内容',
        editFormVisible: false, //控制编辑页面显示与隐藏
        isFormDirty: false,


        // rules表单验证
        rules: {
          id: [
            { required: true, message: '请输入序号', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入指标集名称', trigger: 'blur' }
          ],
          indicators: [
            { required: true, message: '请选择指标', trigger: 'blur' }
          ],
        },
        formInline: {
          id:this.$route.query.id,
          name:this.$route.query.name,
          page: 1,
          limit: 10,

          token: localStorage.getItem('logintoken'),
          tagId: ""
        },

        //指标列表数据
        indicatorIds:'',
        exampleData:[],

        dialogVisible: false,
        dialogTitle: '选择指标',
        selectedIndicators: [], // 用户选择的指标
        editForm: {
          id: this.$route.query.id,
          name:this.$route.query.name,
          indicators:'',
          token: localStorage.getItem('logintoken')
        },
        // 指标集列表
        indicatorListData:[],
        //搜索
        ruleForm: {
          name: '',
          pageNum:'1',
          pageSize:'10',
        },
        isEditing: false, // 控制是否处于编辑状态
      }
    },
    // 注册组件
    components: {
      Pagination
    },

    /**
     * 数据发生改变
     */
    watch: {},

    /**
     * 创建完毕
     */
    created() {
      var data1 = localStorage.getItem('userName');
      var data2 = localStorage.getItem('pwd');
      var data3 = localStorage.getItem('userId');
      this.getSearchPage(this.formInline)
      this.getExample()

    },
    beforeRouteLeave(to, from, next) {
      if (this.isFormDirty) {
        this.$confirm('您有未保存的更改，是否真的要离开？', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            next(); // 用户确认离开，调用 next()
          })
          .catch(() => {
            next(false); // 用户取消离开，调用 next(false) 取消导航
          });
      } else {
        next(); // 如果没有未保存的更改，直接离开
      }
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      check(){

        this.editForm.indicators = this.indicatorListData.map(item => item.indicator).join(",");
        console.log(this.editForm)
       this.$message({
           type: 'success',
           message: this.editForm
         })
      },
      // 编辑
      edit(){
          this.isEditing = true; // 切换编辑状态
      },

      handleDelete(indicator) {
        // 删除操作
        const index = this.indicatorListData.findIndex(item => item.indicator === indicator);
        if (index !== -1) {
          this.$confirm('确认删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.indicatorListData.splice(index, 1);
            this.isFormDirty = true;
            this.$message({
              type: 'success',
              message: '删除成功'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }
      },

      addIndicator() {
        this.dialogVisible = true;
        this.selectedIndicators = []; // 清空之前的选择

      },
      handleSelectChange(value) {
        this.selectedIndicators = value;
      },
      confirmSelection() {
        if (this.selectedIndicators.length > 0) {
          // 标记是否有指标已存在于列表中
          let allIndicatorsNew = true;

          // 遍历选择的数据
          this.selectedIndicators.forEach(indicator => {
            // 检查indicator是否已存在于indicatorListData中
            const isExist = this.indicatorListData.some(item => item.indicator === indicator);

            // 如果有指标已存在，则设置标记为false
            if (isExist) {
              allIndicatorsNew = false;
              // 显示指标已存在的警告消息
              this.$message({
                message: `${indicator} 已存在于列表中`,
                type: 'warning'
              });
            }
          });

          // 如果所有指标都是新的，则添加到表格中
          if (allIndicatorsNew) {
            this.selectedIndicators.forEach(indicator => {
              this.indicatorListData.push({ indicator });
            });
            // 关闭弹窗
            this.dialogVisible = false
            // 清空选择，准备下一次选择
            this.selectedIndicators = [];
            this.isFormDirty = true;
            this.$message({
              message: '添加成功',
              type: 'success'
            });
          }




        } else {
          // 如果没有选择任何指标，显示警告消息
          this.$message({
            message: '请至少选择一个指标',
            type: 'warning'
          });
        }
      },
      // 获取数据方法
      getSearchPage() {
        this.logining = true
        let url = this.$global.javaUrl +"/indicatorList/indicators"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              id:this.formInline.id

            }
        }
        axios.get(url, config).then(response=>{
         const res = response.data.data.split(',')

          this.indicatorListData = res.map(indicator => ({
            indicator:indicator
          }));
          console.log(this.indicatorListData)
        })

      },

      // 编辑、添加提交方法
      save(editData) {
        let config = {
          headers:
            {
              'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            }
        }
        this.editForm.indicators = this.indicatorListData.map(item => item.indicator).join(",");
            // 请求方法
            axios
              .post(this.$global.javaUrl +"/indicatorList/saveOrUpdate",this.editForm,config)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '保存成功'
                });
                // 保存后通常要退出编辑状态
                this.isEditing = false;
                if (res.data.data != null) {
                  this.$message({
                    type: 'success',
                    message: "数据保存成功！"
                  })
                  this.isFormDirty = false;
                  this.getSearchPage()
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('保存失败，请稍后再试！')
              })
      },
      // 获取执行条件
      getExample() {
        this.logining = true
        let url = this.$global.javaUrl+"/target/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              name:'',
              tag:'指标',
              pageNum: '1',
              pageSize:'200',

            }
        }
        axios.get(url, config).then(response=>{

          this.exampleData  = response.data.data.rows.map(item => item.example);


        })
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog == 'edit') {
          this.editFormVisible = false
          this.editForm.id = ''
          this.editForm.name = ''
          this.editForm.indicators = ''
          this.indicatorIds = ''
        } else if (dialog == 'perm') {
          this.dataAccessshow = false
        } else if (dialog == 'unit') {
          this.unitAccessshow = false
        }
      },

      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getSearchPage()
      },
      reset(){
        this.formInline.page = 1
        this.formInline.name = ""
        this.formInline.tag = ""
        this.getSearchPage(this.formInline)
      },

    }
  }
</script>

<style scoped>

  .small-delete-button {
    padding: 2px 5px; /* 调整内边距来减小按钮大小 */
    font-size: 12px; /* 调整字体大小 */
    line-height: 16px; /* 调整行高，确保按钮高度合适 */
  }
  .indicator-table-container {
    background-color: #f5f5f5;
    padding: 20px;
    border-radius: 8px;
  }

  .custom-table {
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .indicator-cell {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }


  .action-buttons {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .button-group {
    margin-left: 10px;
  }/* 根据需要调整左边距 */
  .custom-dialog {
    border-radius: 8px;
  }

  .custom-select {
    width: 100%;
  }
</style>

